package com.beiing.tianshuai.tianshuai.common.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.ReportResultBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.network.DataManager;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.GlideImageLoader;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by LZQ on 2018/1/19.
 * Description: 通用举报页面
 */

public class ReportActivity extends BaseActivity {

    @BindView(R.id.toolbar_iv_back)
    ImageView toolbarIvBack;
    @BindView(R.id.toolbar_tv_submit)
    TextView toolbarTvSubmit;
    @BindView(R.id.rg_report_type)
    RadioGroup rgReportType;
    @BindView(R.id.radio_child_1)
    RadioButton radioChild1;
    @BindView(R.id.radio_child_2)
    RadioButton radioChild2;
    @BindView(R.id.radio_child_3)
    RadioButton radioChild3;
    @BindView(R.id.radio_child_4)
    RadioButton radioChild4;
    @BindView(R.id.radio_child_5)
    RadioButton radioChild5;
    @BindView(R.id.iv_feedback_pic)
    ImageView ivFeedbackPic;
    @BindView(R.id.btn_delete)
    Button btnDelete;
    @BindView(R.id.edit_report_content)
    EditText editReportContent;

    public static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    private String mPhotoPath;
    private String mOutFilePath;
    private CompositeDisposable mCompositeDisposable;
    private String uid;
    private String currency_id;
    private String tid;

    private static final String TAG = ReportActivity.class.getSimpleName();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_report;
    }

    @Override
    protected void init() {
        initData();
        initListener();
    }

    private void initData() {
        mCompositeDisposable = new CompositeDisposable();
        uid = UserInfoBean.getUid(mContext);
        Intent intent = getIntent();
        currency_id = intent.getStringExtra("currency_id");
        tid = intent.getStringExtra("tid");
    }

    private void initListener() {
        // 工具栏 返回
        toolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        // 工具栏 提交
        toolbarTvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        // 图片选择
        ivFeedbackPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkSelfPermission();
            }
        });

        // 删除图片
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(mOutFilePath)) {
                    mOutFilePath = "";
                    ivFeedbackPic.setImageResource(R.mipmap.icon_camera_solid);
                    ivFeedbackPic.setBackgroundColor(ContextCompat.getColor(mContext, R.color.gallery_blue));
                    btnDelete.setVisibility(View.GONE);
                }
            }
        });

        // 提交反馈
        toolbarTvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                File picFile = null;
                int checkedRadioButtonId = rgReportType.getCheckedRadioButtonId();
                String content = editReportContent.getText().toString();
                if (null != mOutFilePath){
                    picFile = new File(mOutFilePath);
                }
                LogUtils.i(checkedRadioButtonId+"", TAG+"checkedRadioButtonId:");
                if (checkedRadioButtonId == -1){
                    showShortText("请选择举报类型");
                } else {
                    RadioButton radioChecked = findViewById(checkedRadioButtonId);
                    String type = radioChecked.getText().toString();
                    submitReport(type, content, picFile);
                }
            }
        });
    }

    private void submitReport(String type, String content, File picFile){
        //构建body
        RequestBody requestBody = null;
        if (null != picFile) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("uid", uid)
                    .addFormDataPart("currency_id", currency_id)
                    .addFormDataPart("type", type)
                    .addFormDataPart("content", content)
                    .addFormDataPart("tid", tid)
                    .addFormDataPart("picname", picFile.getName(), RequestBody.create(MediaType.parse("image/*"), picFile))
                    .build();
        } else {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("uid", uid)
                    .addFormDataPart("currency_id", currency_id)
                    .addFormDataPart("type", type)
                    .addFormDataPart("content", content)
                    .addFormDataPart("tid", tid)
                    .build();
        }

        DisposableObserver<ReportResultBean> observer = new DisposableObserver<ReportResultBean>() {
            @Override
            public void onNext(ReportResultBean reportResultBean) {
                if (reportResultBean.getCode() == 200){
                    showShortText("举报成功");
                }
                finish();
            }

            @Override
            public void onError(Throwable e) {
                LogUtils.i(e.toString(), TAG);
            }

            @Override
            public void onComplete() {

            }
        };

        DataManager.getRepotResult(requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
        mCompositeDisposable.add(observer);
    }

    // 动态权限申请
    private void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            LogUtils.i("需要授权", TAG);
            if (ActivityCompat.shouldShowRequestPermissionRationale(ReportActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                LogUtils.i("拒绝过了", TAG);
                // 提示用户如果想要正常使用，要手动去设置中授权。
                showShortText("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
                LogUtils.i("进行授权", TAG);
                ActivityCompat.requestPermissions(ReportActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            LogUtils.i("不需要授权", TAG);
            // 进行正常操作
            selectImage();
        }
    }

    // 选择图片
    private void selectImage() {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                mPhotoPath = photoList.get(0);
                LogUtils.i(photoList.toString(), TAG);
                Tiny.FileCompressOptions tinyOptions = new Tiny.FileCompressOptions();
                Tiny.getInstance().source(mPhotoPath).asFile().withOptions(tinyOptions).compress(new FileCallback() {
                    @Override
                    public void callback(boolean isSuccess, String outfile) {
                        if (isSuccess) {
                            RequestOptions options = new RequestOptions()
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .centerCrop();
                            Glide.with(mContext.getApplicationContext())
                                    .load(outfile)
                                    .apply(options)
                                    .into(ivFeedbackPic);
                            ivFeedbackPic.setBackgroundColor(ContextCompat.getColor(mContext, R.color.transparent));
                            mOutFilePath = outfile;
                            btnDelete.setVisibility(View.VISIBLE);
                            File file = new File(outfile);
                            long length = file.length();
                            LogUtils.i("File length : " + length, TAG);
                        } else {
                            showShortText("图片过大");
                        }
                    }
                });
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(false)                                 // 是否多选   默认：false
                .crop(false)                                        // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(ReportActivity.this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCompositeDisposable.clear();
    }
}
